"""
python爬取网易云热歌榜歌曲

模块：
    requests   >>> pip install requests
    re
    os

- 数据来源：
    https://music.163.com/discover/toplist?id=3778678
"""
import requests
import re
import os


fileName = 'music/'

if not os.path.exists(fileName):
    os.makedirs(fileName)


# 如果想要爬取其他榜单的内容，只需要更改请求 url 查询参数的id即可
url = 'https://music.163.com/discover/toplist'
# 请求头
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) "
                  "Chrome/54.0.2840.99 Safari/537.36 "
}

params = {
    'id': '3778678'
}

response = requests.get(url=url, params=params, headers=headers)
html_data = re.findall('<li><a href="/song\?id=(\d+)">(.*?)</a>', response.text)
for num_id,title in html_data:
    # https://music.163.com/song/media/outer/url?id=1824045033.mp3
    music_url = f'https://music.163.com/song/media/outer/url?id={num_id}.mp3'
    music_content = requests.get(url=music_url, headers=headers).content
    with open('music/'+title+'.mp3', mode='wb') as f:
        f.write(music_content)
    break

